import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false })
const whiteList = ['/login']

// router.beforeEach(async(to, from, next) => {
//   NProgress.start()
//   document.title = getPageTitle(to.meta.title)

//   const hasToken = getToken()

//   if (hasToken) {
//     if (to.path === '/login') {
//       next({ path: '/' })
//       NProgress.done()
//     } else {
//       const hasRoles = store.getters.roles && store.getters.roles.length > 0
//       if (hasRoles) {
//         next()
//       } else {
//         try {
//           const { roles } = await store.dispatch('user/getInfo')
//           const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
//           router.addRoutes(accessRoutes)
//           next({ ...to, replace: true })
//         } catch (error) {
//           await store.dispatch('user/resetToken')
//           Message.error(error || 'Has Error')
//           next(`/login?redirect=${to.path}`)
//           NProgress.done()
//         }
//       }
//     }
//   } else {
//     if (whiteList.indexOf(to.path) !== -1) {
//       next()
//     } else {
//       next(`/login?redirect=${to.path}`)
//       NProgress.done()
//     }
//   }
// })
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  if (to.path === '/login' || to.path === '/404') {
    // 前往了login页需要清空的东西
    store.dispatch('media/resetState') // 清空媒体相关列表
    next()
    NProgress.done()
  } else {
    const token = getToken()
    if (token) {
      if (to.path === '/dashboard') {
        next()
        NProgress.done()
      } else {
        const menuArray = store.getters.permission_routes
        console.log(menuArray,'menuArray===========')
        menuArray.forEach(item => {
          if (item.children && item.children.length > 0) {
            var doNext = false
            item.children.forEach(childItem => {
              if (to.path === childItem.path) {
                doNext = true
              }
            })
            if (!doNext) {
              whiteList.forEach(item => {
                if (to.path === item) {
                  doNext = true
                }
              })
            }
            if (doNext) {
              next()
              NProgress.done()
            }
          } else {
            next()
            NProgress.done()
          }
        })
      }
    } else {
      next({
        path: '/login',
        query: {
          redirect: to.fullPath
        }
      })
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
